<?php

namespace App\Http\Middleware;

use App\Common\Func;
use App\Models\AppPackageModel;
use App\Models\UserModel;
use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

/**
 *
 * - author llc
 *
 */
class AppRequestLog
{
    public static $exceptAction = [

    ];

//    /**
//     * @var UserActiveService
//     */
//    private UserActiveService $userActiveService;
//
//    public function __construct(UserActiveService $userActiveService)
//    {
//        $this->userActiveService = $userActiveService;
//    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        self::setXInfo($request->header());
        return $next($request);
    }

    public function terminate($request, $response)
    {
        $startTime = LARAVEL_START * 1000;
        $endTime = microtime(true) * 1000;
        $url = $request->getRequestUri();
        $header = $request->header();
        $allRequest = $request->all();
        $allInfo = [
            'url' => $url,
            'input' => $request->input(),
            'response' => json_decode($response->getContent(), true),
            'header' => $header,
            'allRequest' => $allRequest,
            'microtime' => microtime(),
            'start_time' => $startTime,
            'end_time' => $endTime,
            'handle_time' => intval(($endTime - $startTime))
        ];
        if (in_array($url, self::$exceptAction)) {
            $allInfo['response'] = [];
        }
        if ($_SERVER['REMOTE_ADDR']) {
            try {
                $deviceId = Session::get('deviceId');
                $location = Func::getLocationByIP($_SERVER['REMOTE_ADDR']);
                $userIdCacheKey = "location:userId:" . $deviceId;
                if ($location) {
                    Cache::put($userIdCacheKey, json_encode($location, JSON_UNESCAPED_UNICODE), 3600 * 24 * 30);
                }
            } catch (\Exception $e) {
                Func::logError("");
            }
        }
        Func::logInfo($allInfo, '请求日志');
    }

    public function setXInfo($header)
    {
        Session::put([
            'deviceId' => isset($header['x-device-id']) ? $header['x-device-id'][0] : null,
            'uuid' => isset($header['x-uuid']) ? $header['x-uuid'][0] : null,
            'imei' => isset($header['x-imei']) ? $header['x-imei'][0] : null,
            'clientModel' => isset($header['x-client-model']) ? $header['x-client-model'][0] : null,
            'systemVersion' => isset($header['x-system-version']) ? $header['x-system-version'][0] : null,
        ]);
    }
}
